import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as SellChanceMainAction from '../../actions/sellChanceMain'
import forEach from 'lodash/forEach'
import isEmpty from 'lodash/isEmpty'

import WeaCrmTableEdit from '../WeaCrmTableEdit'
import CrmTools from '../crmTools';

import {
    WeaSearchGroup,
    WeaRightMenu,
    WeaTop
} from 'ecCom'

import {WeaErrorPage,WeaTools} from 'ecCom'

import {Button,Form,Modal,message} from 'antd' 
const createForm = Form.create;
const FormItem = Form.Item;

import cloneDeep from 'lodash/cloneDeep'
import objectAssign from 'object-assign'
import equal from 'deep-equal'
import PropTypes from 'react-router/lib/PropTypes'
import Immutable from 'immutable'
const is = Immutable.is;

let _this = null;

class AddSellChance extends React.Component {
    constructor(props) {
		super(props);
        _this = this;
        this.state={
            datas:[],
            required:[]
        }
    }
    componentDidMount() {
        const {actions} = this.props;
        //  actions.setNowRouterCmpath('contactQuery');
        actions.sellChanceForm({operation:"add"});
    }
    componentWillReceiveProps(nextProps) {
        if(this.props.key !== nextProps.key){
            const {actions} = this.props;
            //  actions.setNowRouterCmpath('contactQuery');
            actions.sellChanceForm({operation:"add"});
        }
    }
    shouldComponentUpdate(nextProps,nextState) {
        return !is(this.props.title,nextProps.title)||
        !is(this.props.mainTableInfo,nextProps.mainTableInfo)||
        !is(this.props.subTableInfo,nextProps.subTableInfo)||
        !is(this.props.loading,nextProps.loading)
        !is(this.props.subTableColumn,nextProps.subTableColumn)||
        !is(this.props.addOrderFields,nextProps.addOrderFields)||
        !is(this.props.addParamsAd,nextProps.addParamsAd)||
        !is(this.props.closeAddPage,nextProps.closeAddPage)||
        !is(this.props.key,nextProps.key)||
        !equal(this.state.datas,nextState.datas);
    }
    componentWillUnmount(){
    	// const {actions,isClearNowPageStatus} = this.props;
        // actions.unmountClear(isClearNowPageStatus);
        // actions.isClearNowPageStatus(false);
    }
    render() {
        let that = this;
        const {loading,actions,title,mainTableInfo,subTableInfo,subTableColumn,closeAddPage} = this.props;
        const columns = subTableInfo.get('columnDefine');
        const dataSource = subTableInfo.get('columnData');
        return (
            <div>
               <WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
                     <WeaTop 
                        title={"商机"}
                        loading={loading}
                        icon={<i className='icon-coms-crm' />}
                        iconBgcolor='#96358a'
                        buttons={this.getButtons()}
                        buttonSpace={10}
                        showDropIcon={true}
                        dropMenuDatas={this.getRightMenu()}
                        onDropMenuClick={this.onRightMenuClick.bind(this)}
                        selectedKey={'main'}
                        onChange={()=>{}}
                    >
                        <Form horizontal>{this.getBasicInfo()}</Form>
                        <WeaCrmTableEdit 
                            title={"产品"} 
                            showGroup={true} 
                            needAdd={true} 
                            needCopy={false}
                            columns={subTableColumn.toJS()} 
                            datas={dataSource.toJS()}
                           onChange={this.editTableDatas.bind(this)}
                        />
                    </WeaTop>
               </WeaRightMenu>
            </div>
        )
    }
     onRightMenuClick(key){
    	 const {actions,} = this.props;
    	if(key == '0'){
            this.saveNewSellChance();
    	}
    	if(key == '1'){
    		// actions.batchSubmitClick({checkedKeys:`${selectedRowKeys.toJS()}`})
    	}
    }
    getRightMenu(){
    	// const {comsWeaTable,sharearg,actions} = this.props;
    	// const selectedRowKeys = comsWeaTable.get('selectedRowKeys');
        // const hasBatchBtn = sharearg && sharearg.get("hasBatchBtn");
    	let btns = [];
    	btns.push({
    		icon: <i className='icon-Right-menu-search'/>,
            content:'保存',
            key:0
    	});
        btns.push({
    		icon: <i className='icon-Right-menu-Custom'/>,
    		content:'返回'
    	});
        btns.push({
            icon: <i className='icon-Right-menu-batch'/>,
            content:'收藏',
        });
    	btns.push({
            icon: <i className='icon-Right-menu-batch'/>,
            content:'帮助',
        });
    	return btns
    }
     getButtons() {
        let btnArr = [];
       btnArr.push(<Button type="primary" onClick={this.saveNewSellChance}>保存</Button>)

        return btnArr
    }
    getBasicInfo=()=> {
       const { mainTableInfo,actions } = this.props;
        let group = [];
        let viewObj = [];
		mainTableInfo.toJS().map(c =>{
			let items = [];
			c.items.map(field => {
                let fit = field.formItemType.toUpperCase();
                if(fit != "BROWSER" && field.viewAttr == "3"){
                    viewObj.push(field.domkey[0]);
                }else if(fit == "BROWSER"){
                    const bcp = field.browserConditionParam;
                    if(bcp.viewAttr == "3"){
                       viewObj.push(field.domkey[0]);
                    }  
                }
                items.push({
                    com:(<FormItem
                        label={`${field.label}`}
                        labelCol={{span: `${field.labelcol}`}}
                        wrapperCol={{span: `${field.fieldcol}`}}>
                            { WeaTools.getComponent(field.formItemType, field.browserConditionParam, field.domkey, this.props, field)}
                        </FormItem>),
                    colSpan:1
                })
			});
			group.push(<WeaSearchGroup needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
        }); 
        this.setState({required:viewObj})
		return group
    }

    editTableDatas(datas){
        this.setState({datas})

    }
    saveNewSellChance=()=>{
        const {actions,addParamsAd,closeAddPage} = this.props;
        const {datas,required} = this.state;
        let _value = {};
        const _addParams = addParamsAd.toJS();
        const require = (function(){
             for(let i=0;i<required.length;i++){
                if(!_addParams[required[i]]){
                    return false
                }
             }
            return true;
        })(); 
        const listRequire = (function(){
            if(datas.length>0){
                _value.productList =JSON.stringify(datas);
                for(let i=0;i<datas.length;i++){
                    if(!datas[i].productid || !datas[i].currencyid){
                        return false;
                    }
                }
            }
            return true;
        })();
        if(require && listRequire){
            actions.createSellChance({..._addParams,..._value});
            this.closeWindow();
            {typeof this.props.createCallBack === 'function' && this.props.createCallBack();}
        }else{
            Modal.warning({
                title: '系统提示',
                content: '必填信息不完整!',
            });
        }
    }
    closeWindow=()=>{
        const {closeAddPage} = this.props;
        if(closeAddPage){
            window.top.opener = null;
            window.close();
            return true;
        }
    }
   
}


class MyErrorHandler extends React.Component {
    render(){
        const hasErrorMsg = this.props.error && this.props.error!=="";
        return (
            <WeaErrorPage msg={hasErrorMsg?this.props.error:"对不起，该页面异常，请联系管理员！"} />
        );
    }
}

AddSellChance = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(AddSellChance);

AddSellChance = createForm({
	onFieldsChange(props, fields) {
        props.actions.saveAddOrderFields({...props.addOrderFields.toJS(), ...fields});
    },
	mapPropsToFields(props) {
		return props.addOrderFields.toJS();
  	}
})(AddSellChance);

function mapStateToProps(state) {
    const {crmsellChanceMain} = state;
    return {
    	loading: crmsellChanceMain.get('loading'),
        title: crmsellChanceMain.get('title'),
        mainTableInfo: crmsellChanceMain.get('mainTableInfo'),
        subTableInfo: crmsellChanceMain.get('subTableInfo'),
        subTableColumn:crmsellChanceMain.get('subTableColumn'),
        addOrderFields:crmsellChanceMain.get('addOrderFields'),
        addParamsAd:crmsellChanceMain.get('addParamsAd'),
        closeAddPage:crmsellChanceMain.get('closeAddPage'),
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators({...SellChanceMainAction}, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(AddSellChance);
